package com.l.web.service.system.webnode;

import com.l.web.service.ServiceSupport;
import org.apache.log4j.Logger;
import org.l.qiao.Cluster;
import org.l.qiao.ClusterUtil;
import org.l.qiao.Validate;
import org.l.qiao.search.Field;
import org.l.qiao.search.Query;
import org.l.qiao.search.Sort;

import java.util.ArrayList;
import java.util.List;

public class WebNodeDetailService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(WebNodeDetailService.class);
    private WebNodeDAO webNodeDAO;

    public void setWebNodeDAO(WebNodeDAO webNodeDAO) {
        this.webNodeDAO = webNodeDAO;
    }

    public String execute() {
        String id = form.getString("id");
        LOGGER.debug("id=" + id);

        if (Validate.check(Validate.OBJECTID, id)) {
            Cluster webNode = webNodeDAO.findById(id);

            if (webNode.isEmpty()) {
                LOGGER.error("所查看的栏目不存在");
                error(404);
                return NONE;
            }

            context.put("webNode", webNode);
            context.put("check", ClusterUtil.getCheck(WebNode.class));
            findParents(webNode);
            return DETAIL;
        } else {
            error(404);
            LOGGER.error("错误参数：id=" + id);
            return NONE;
        }
    }

    private void findParents(Cluster webNode) {
        Query query = new Query();
        query.in(WebNode.ID, webNode.getList(WebNode.PARENT, new ArrayList()));
        Field field = new Field(WebNode.NAME);
        Sort sort = new Sort();
        sort.asc(WebNode.DEEP);
        List parents = webNodeDAO.find(query, field, sort);
        context.put("parents", parents);
    }
}
